// map-manage.js
(function() {
    // 地图配置
    const MAP_CONFIG = {
        containerId: 'map_container',
        center: { lat: 28.649902, lng: 115.827733 },
        zoom: 20,
        language: 'zh',
        sourceType: 'raster',
        controls: {
            scale: true,
            rotate: true
        },
        style: 'simple',
        marker: {
            label: {
                text: 'JTAC',
                offsetY: -30,
                color: '#ffffff'
            },
            icon: {
                opacity: 0.5,
                scale: 1.2,
                color: '#0c0c0c'
            }
        }
    };

    // 全局地图对象
    window.globalMap = null;
    window.globalMarker = null;

    /**
     * 初始化地图并暴露全局对象
     * @throws {Error} 地图初始化失败时抛出错误
     */
    window.initMap = function() {
        try {
            // 初始化地图实例
            window.globalMap = new HWMapJsSDK.HWMap(
                document.getElementById(MAP_CONFIG.containerId),
                getMapOptions()
            );

            // 初始化标记
            window.globalMarker = new HWMapJsSDK.HWMarker({
                map: window.globalMap,
                position: MAP_CONFIG.center,
                label: MAP_CONFIG.marker.label,
                icon: MAP_CONFIG.marker.icon
            });

            // 调试日志
            console.log('Map initialized successfully');

            // 触发自定义事件
            const event = new CustomEvent('map-initialized', {
                detail: {
                    map: window.globalMap,
                    marker: window.globalMarker
                }
            });
            document.dispatchEvent(event);
        } catch (error) {
            console.error('地图初始化失败:', error);
            showErrorAlert();
            throw new Error('Map initialization failed');
        }
    };

    // 获取地图配置选项
    function getMapOptions() {
        return {
            center: MAP_CONFIG.center,
            zoom: MAP_CONFIG.zoom,
            language: MAP_CONFIG.language,
            sourceType: MAP_CONFIG.sourceType,
            scaleControl: MAP_CONFIG.controls.scale,
            rotateControl: MAP_CONFIG.controls.rotate,
            presetStyleId: MAP_CONFIG.style
        };
    }

    // 显示错误提示
    function showErrorAlert() {
        const container = document.getElementById(MAP_CONFIG.containerId);
        if (container) {
            container.innerHTML = `
                <div class="map-error">
                    <h3>地图加载失败</h3>
                    <p>可能原因：</p>
                    <ul>
                        <li>网络连接不可用</li>
                        <li>浏览器不支持WebGL</li>
                        <li>地图服务暂时不可用</li>
                    </ul>
                </div>
            `;
        }
    }

    // 自动初始化（可选）
    if (document.readyState === 'complete') {
        window.initMap();
    } else {
        window.addEventListener('load', window.initMap);
    }
})();